<template>
  <yt-page :leftData="leftData" :more.sync="more" title="智慧安监">
    <ul class="ul" slot="more">
      <li @click="handler(key)" v-for="(tab, key) in TABS" :key="key">{{tab}}</li>
    </ul>
    <yt-tabbar v-model="page" :slider="false">
      <yt-tabbar-panel text="首页" font="iconfont icon-main">
        <yt-slider class="slider" v-model="slider" :list="sliders" dots>
          <div class="item" slot-scope="scope">
            <img :src="scope.data.img">
          </div>
        </yt-slider>
        <div class="list">
          <div class="item yt-border-all" @click="goPage('/message')">
            <div class="item-icon-left bg1">
              <i class="iconfont icon-message"></i>
            </div>
            <div class="content">
              <p class="title">通知公告</p>
              <p class="des">请前往详情页查看更多公告！</p>
            </div>
          </div>
          <div v-show="todoObj" class="item yt-border-all" @click="goTodoPage(todoObj)">
            <div class="item-icon-left bg2">
              <i class="iconfont icon-list"></i>
            </div>
            <div class="content">
              <p class="title">待办事项<span>{{todoObj ? todoObj.todo_time : ''}}</span></p>
              <p class="des">{{todoObj ? todoObj.todo_content : ''}}</p>
            </div>
          </div>
          <div class="item yt-border-all" v-if="emergencyObj" @click="goEmergencyPage">
            <div class="item-icon-left bg3">
              <i class="iconfont icon-danger"></i>
            </div>
            <div class="content">
              <p class="title">应急救援<span>{{emergencyObj.updatedAt | formatTime('YYYY-MM-DD HH:mm:ss')}}</span></p>
              <p class="des">{{ emergencyObj.enterprise_name && emergencyObj.enterprise_name.attributes.EnterpriseName
                }}({{ emergencyObj.accident_type }})</p>
            </div>
          </div>
        </div>
      </yt-tabbar-panel>
      <yt-tabbar-panel text="功能菜单" font="iconfont icon-menu">
        <yt-grid :x="3" :y="5" :list="grids">
          <yt-grid-item slot-scope="data" v-bind="data" @click="goPage(data.path)"></yt-grid-item>
        </yt-grid>
      </yt-tabbar-panel>
      <yt-tabbar-panel text="个人中心" font="iconfont icon-person">
        <yt-cell label="头像">
          <img class="avatar" :src="user.avatar_path || require('./avatar.png')">
        </yt-cell>
        <yt-cell label="账户名称" :value="user.username" />
        <yt-cell label="联系方式" :value="user.tel" />

        <yt-cell label="当前版本" value="已是最新版本"></yt-cell>
        <yt-split></yt-split>
        <yt-cell label="修改个人资料" labelWidth="70%" isLink @click="goPage('/base/personal')"></yt-cell>
        <!-- <yt-cell label="产品服务" isLink @click="goPage('/base/productService')"></yt-cell> -->

        <yt-btn theme="red" class="m-t" @click="logout">退出登录</yt-btn>
      </yt-tabbar-panel>
    </yt-tabbar>
  </yt-page>
</template>

<script>
import { BaseUrl, IP } from '@/config'
import { SetStore, GetStore, Store, JudgeRole } from '@/store'
import { commonApi } from '@/common/api/commonApi.js'
import { ReplaceDictionary } from '@/common/utils/index.js'
import { bridge } from '@/common/plugin/utils/bridge'

const TABS = {
  public: '外网IP',
  private: '内网IP',
  local: '本地IP'
}
export default {
  name: 'page-home',
  data() {
    return {
      TABS,
      more: false,
      leftData: [],
      rightData: [
        {
          font: 'yt-icon yt-icon-more',
          click: () => {
            this.more = !this.more
          }
        }
      ],
      page: 0,
      slider: 0,
      sliders: [
        {
          img: require('./slider-pic.png')
        }
      ],
      grids: [],
      emergencyObj: null,
      todoObj: {},
      user: {},
      userRole: '',
      enterpriseId: ''
    }
  },
  mounted() {},
  async activated() {
    let grids = [
      {
        font: 'iconfont icon-law',
        text: '行政执法',
        path: '/law'
      },
      {
        font: 'iconfont icon-list',
        // badge: {value: 120},
        text: '待办事项',
        path: '/todo'
      },
      {
        font: 'iconfont icon-company',
        text: '企业信息',
        path: '/company'
      },
      {
        font: 'iconfont icon-check',
        text: '重大危险源',
        path: '/danger-source-check'
      },
      {
        font: 'iconfont icon-data',
        text: '知识库',
        path: '/repository'
      },
      {
        font: 'iconfont icon-machine',
        text: '应急救援',
        path: '/emergency'
      },
      {
        font: 'iconfont icon-line',
        text: '统计分析',
        path: '/analysis'
      },
      {
        font: 'iconfont icon-phone',
        text: '通讯联络',
        path: '/contact'
      },
      // {
      //   font: 'iconfont icon-author',
      //   text: '专家库',
      //   path: '/professional'
      // },
      // {
      //   font: 'iconfont icon-card',
      //   text: '人员工卡',
      //   path: '/work-card'
      // },
      {
        font: 'iconfont icon-contact',
        text: '二道门',
        path: '/twoDoor'
      },
      {
        font: 'iconfont icon-machine-2',
        text: '特殊作业',
        path: '/special-work'
      },
      {
        font: 'iconfont icon-danger',
        text: '隐患排查',
        path: '/dangerCheck'
      },
      {
        font: 'iconfont icon-anquanzhenggaioff',
        text: '安全风险',
        path: '/security-risk'
      }
    ]
    this.enterpriseId = JudgeRole()
      .administrator(() => {
        this.grids = grids
        this.userRole = 'administrator'
      })
      .enterprise(() => {
        // 企业端登陆没有行政执法模块和统计分析模块
        this.grids = grids.filter(
          v => v.text !== '行政执法' && v.text !== '统计分析'
        )
        this.userRole = 'enterprise'
        return (GetStore(Store.enterprise) || {}).id
      })
      .government(() => {
        this.grids = grids
        this.userRole = 'government'
      })
      .default(() => {
        this.grids = grids
        this.userRole = ''
      })

    let user = GetStore(Store.user)
    this.user = await commonApi.searchById('User', user.id)
    SetStore(Store.user, this.user)

    bridge.pushBind({userName: this.user.username, userId: this.user.id})
    console.log(this.user.username + this.user.id)

    this.initData()
    this.initTodoData()
  },
  methods: {
    handler(key) {
      SetStore(IP, BaseUrl[key])
      this.more = !this.more
    },
    goPage(path) {
      //企业端登陆
      if (path === '/company' && this.enterpriseId) {
        this.$router.$push({
          path: '/company/detail',
          query: { id: this.enterpriseId }
        })
      } else if (path === '/special-work' && this.enterpriseId) {
        this.$router.$push({
          path: '/special-work/list',
          query: { req_departName: this.enterpriseId }
        })
      } else if (path === '/dangerCheck' && this.enterpriseId) {
        this.$router.$push({
          path: '/dangerCheck/list',
          query: { state: 1, enterprise_name: this.enterpriseId, supervise: 1 }
        })
      } else if (path === '/security-risk' && this.enterpriseId) {
        this.$router.$push({
          path: '/security-risk/list',
          query: { user: this.enterpriseId }
        })
      } else if (path === '/twoDoor' && this.enterpriseId) {
        this.$router.$push({
          path: '/twoDoor',
          query: { enterpriseId: this.enterpriseId }
        })
      } else {
        this.$router.$push(path)
      }
    },
    goTodoPage(item) {
      const TodoCategory = [
        '行政执法',
        '收发文件',
        '通知公告',
        '企业隐患排查',
        '特殊作业',
        '综合考评',
        '企业注册审核',
        '其他'
      ]

      if (item.todo_category === '行政执法') {
        this.$router.$push('/law')
      } else if (
        item.todo_category === '收发文件' ||
        item.todo_category === '通知公告' ||
        item.todo_category === '会议通知'
      ) {
        this.$router.$push('/message')
      } else if (item.todo_category === '企业隐患排查') {
        this.$Toast('请登录pc端系统，及时处理！')
        this.$router.$push('/dangerCheck')
      } else if (item.todo_category === '特殊作业') {
        this.$router.$push('/special-work')
      } else if (item.todo_category === '企业注册审核') {
        this.$router.$push('/company/register')
      } else {
        // 其他类型暂不支持
      }
    },
    async initData() {
      let param = this.enterpriseId
        ? {
            equalTo: { enterpriseId: this.enterpriseId },
            notEqualTo: { state: 2 }
          }
        : { notEqualTo: { state: 2 } }
      let p = [
        commonApi.dictionary('Accident_type'),
        commonApi.searchFirst('yj_emergency_information', {
          include: ['enterprise_name'],
          ...param
        })
      ]
      let [accidentTypeDic, emergencyObj] = await Promise.all(p)
      emergencyObj._accident_type = emergencyObj.accident_type
      this.emergencyObj = ReplaceDictionary(emergencyObj, {
        accident_type: accidentTypeDic
      })
    },
    async initTodoData() {
      const user = GetStore(Store.user)
      const roles = GetStore(Store.roles)
      const options = {
        and: [
          {
            or: [
              { containedIn: { todo_role: roles.map(v => v.name) } },
              { containedIn: { todo_id: [user.id] } }
            ]
          },
          {
            notContainedIn: { todo_category: ['综合考评', '其他'] }
          },
          {
            equalTo: { todo_state: 0 }
          }
        ]
      }
      this.todoObj = await commonApi.searchFirst('sys_todo', options)
      let todoCount = await commonApi.searchCount('sys_todo', options)
      this.grids.map(v => {
        if (v.text === '待办事项') {
          return { ...v, badge: { value: todoCount } }
        }
      })
    },
    goEmergencyPage() {
      this.$router.$push({
        path: '/emergency/info',
        query: {
          id: this.emergencyObj.id,
          title: this.emergencyObj.enterprise_name.attributes.EnterpriseName || '应急救援'
        }
      })
    },
    logout() {
      commonApi.logout()
      const user = GetStore(Store.user)
      bridge.pushUnBind({userName: user.username, id: user.id})
      this.$router.$push({
        path: '/login'
      })
    }
  }
}
</script>

<style scoped lang="stylus">
.ul
  min-width 120px

  li
    padding 0 15px
    color #333333
    font-size 14px
    height 40px
    line-height 40px
    text-align center
    box-sizing border-box
    border-bottom 1px solid #f1f1f1

    &:last-child
      border-bottom 0

    &:active
      background-color #f5f5f5

.bg1
  background #00bcd4

.bg2
  background #e282fa

.bg3
  background #ff5722

.m-t
  margin-top 20px

.avatar
  display inline-block
  width 60px
  height 60px
  margin 10px
  border-radius 50%

.slider
  height auto

  img
    max-width 100%

.list
  .item
    background-color #fff
    display flex
    justify-content space-between
    align-items center
    padding 10px

    // border-bottom .5px solid #f5f5f5
    &-icon-left
      width 60px
      height 60px
      display flex
      justify-content center
      color white
      margin 0 15px
      align-items center
      border-radius 50%

      .iconfont
        font-size 35px

    .content
      font-size 13px
      color #707070
      line-height 30px
      flex-grow 1
      max-width 70%

      .des
        text-overflow ellipsis
        overflow hidden
        white-space nowrap

      .title
        color #000
        font-size 17px

        span
          float right
          font-size 12px
          color #aaa
          line-height 30px
</style>
